package com.ruoyi.teaching.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.li.work.mapper.SysUserMapper;
import com.ruoyi.teaching.domain.*;
import com.ruoyi.teaching.domain.vo.FeedbackLikeVO;
import com.ruoyi.teaching.domain.vo.PlatformFLikeVO;
import com.ruoyi.teaching.mapper.PlatformFFeedbackLikeMapper;
import com.ruoyi.teaching.mapper.PlatformFFeedbackMapper;
import com.ruoyi.teaching.mapper.PlatformFForumMapper;
import com.ruoyi.teaching.service.PlatformFFeedbackLikeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.teaching.utils.UniversalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 王旭
 * @since 2025-02-12
 */
@Service
public class PlatformFFeedbackLikeServiceImpl extends ServiceImpl<PlatformFFeedbackLikeMapper, PlatformFFeedbackLike> implements PlatformFFeedbackLikeService {
    @Autowired
    private PlatformFFeedbackLikeMapper feedbackLikeMapper;
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private PlatformFFeedbackMapper feedbackMapper;

    /**
     * 整个Impl根据论坛点赞修改
     */
    @Override
    public AjaxResult addFeedbackLike(Long objectId) {
        // 获取当前用户信息
        UniversalCreateUpdate update = UniversalUtil.getCreateUpdate(userMapper);
        Long userId = Long.valueOf(update.getId());

        // 先检查内容是否存在
        PlatformFFeedback platformFFeedback = feedbackMapper.selectById(objectId);
        if (platformFFeedback == null) {
            return AjaxResult.error("当前内容不存在");
        }

        // 检查是否已经点亮（不需要加锁）
        QueryWrapper<PlatformFFeedbackLike> likeQueryWrapper = new QueryWrapper<>();
        likeQueryWrapper.eq("object_id", objectId);
        likeQueryWrapper.eq("create_id", update.getId());
        List<PlatformFFeedbackLike> platformFFeedbackLikes = feedbackLikeMapper.selectList(likeQueryWrapper);
        if (CollectionUtils.isNotEmpty(platformFFeedbackLikes)) {
            return new AjaxResult(HttpStatus.SUCCESS, "点亮成功");
        }

        // 锁定用户 ID，防止重复点亮的并发问题
        synchronized (userId.toString().intern()) {
            // 再次检查是否已点亮，防止在获取锁前其他线程已经执行了点亮操作
            List<PlatformFFeedbackLike> platformFLikeListAfterLock = feedbackLikeMapper.selectList(likeQueryWrapper);
            if (CollectionUtils.isNotEmpty(platformFLikeListAfterLock)) {
                return new AjaxResult(HttpStatus.SUCCESS, "点亮成功");
            }

            // 新增点亮记录
            PlatformFFeedbackLike platformFLike = new PlatformFFeedbackLike();
            platformFLike.setObjectId(objectId);
            platformFLike.setLikeToId(Long.valueOf(platformFFeedback.getCreateId()));
            platformFLike.setLikeType(platformFFeedback.getTopId() == null ? 0 : 1);
            platformFLike.setCreateBy(update.getName());
            platformFLike.setCreateTime(DateUtils.getNowDate());
            platformFLike.setCreateId(update.getId());
            int i = feedbackLikeMapper.insert(platformFLike);
            if (i > 0) {
                // 修改帖子表点亮总数
                QueryWrapper<PlatformFFeedbackLike> platformFLikeQueryWrapper = new QueryWrapper<>();
                platformFLikeQueryWrapper.eq("object_id", objectId);
                List<PlatformFFeedbackLike> platformFLikes = feedbackLikeMapper.selectList(platformFLikeQueryWrapper);
                PlatformFFeedback platformFForumUpdate = new PlatformFFeedback();
                platformFForumUpdate.setId(objectId);
                platformFForumUpdate.setLikeNum(platformFLikes.size());
                feedbackMapper.updateById(platformFForumUpdate);
                return new AjaxResult(HttpStatus.SUCCESS, "点亮成功");
            } else {
                return new AjaxResult(HttpStatus.ERROR, "点亮失败");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult cancelFeedbackLike(Long[] ids) {
        for (Long id : ids) {
            QueryWrapper<PlatformFFeedbackLike> platformFFeedbackLikeQueryWrapper = new QueryWrapper<>();
            platformFFeedbackLikeQueryWrapper.eq("object_id", id);
            platformFFeedbackLikeQueryWrapper.eq("create_id", SecurityUtils.getUserId());
            int i1 = feedbackLikeMapper.delete(platformFFeedbackLikeQueryWrapper);
            if (i1 == 0) {
                throw new RuntimeException("取消点量失败");
            }
            QueryWrapper<PlatformFFeedbackLike> platformFLikeQueryWrapper = new QueryWrapper<>();
            platformFLikeQueryWrapper.eq("object_id", id);
            List<PlatformFFeedbackLike> platformFLikes = feedbackLikeMapper.selectList(platformFLikeQueryWrapper);
            PlatformFFeedback platformFForum1 = new PlatformFFeedback();
            platformFForum1.setId(id);
            platformFForum1.setLikeNum(platformFLikes.size());
            feedbackMapper.updateById(platformFForum1);
            return new AjaxResult(HttpStatus.SUCCESS, "取消点亮成功");
        }
        throw new RuntimeException("取消点亮失败");
    }

    @Override
    public AjaxResult getPersonalLike(Integer pageNum, Integer pageSize, Integer type) {
        Page<PlatformFFeedbackLike> platformFLikePage = new Page<>(pageNum, pageSize);

        QueryWrapper<PlatformFFeedbackLike> likeQueryWrapper = new QueryWrapper<>();
        Long userId = SecurityUtils.getUserId();
        likeQueryWrapper.eq(type != null ? (type == 0 ? "create_id" : "like_to_id") : "create_id", userId)
                .orderByDesc("create_time");
        platformFLikePage = feedbackLikeMapper.selectPage(platformFLikePage, likeQueryWrapper);

        Page<FeedbackLikeVO> platformFLikeVOPage = new Page<>(pageNum, pageSize);
        BeanUtils.copyProperties(platformFLikePage, platformFLikeVOPage);

        List<FeedbackLikeVO> likeVOList = new ArrayList<>();
        for (PlatformFFeedbackLike record : platformFLikePage.getRecords()) {
            PlatformFFeedback platformFFeedback = feedbackMapper.selectById(record.getObjectId());
            FeedbackLikeVO likeVO = new FeedbackLikeVO();

            BeanUtils.copyProperties(record, likeVO);
            if (null == type) {
                type = 0;
            } else if (type > 1) {
                type = 0;
            }

            if (platformFFeedback != null) {
                // 若点亮对象为帖子/评论，设置点亮对象的创建者名称
                String myCreate = platformFFeedback.getCreateBy();
                String forMe = record.getCreateBy();
                String message = platformFFeedback.getMessage();
                if (Math.toIntExact(userId) == record.getCreateId()) {
                    forMe = "我";
                }
                if (Math.toIntExact(userId) == platformFFeedback.getCreateId()) {
                    myCreate = "我";
                }
                likeVO.setLikeToName(myCreate);

                // 根据点亮类型（0: 帖子, 1: 评论）设置对应的标题或内容

                if (record.getLikeType() == 0) {
                    likeVO.setCommentTitle(type == 0 ? "我点亮了" + myCreate + "发布的帖子：" + message : forMe + "点亮了我发布的帖子：" + message); // 帖子标题
                } else {
                    likeVO.setCommentTitle(type == 0 ? "我点亮了" + myCreate + "发布的评论：" + message : forMe + "点亮了我发布的评论：" + message); // 评论内容
                }
            } else {
                // 若点亮对象不存在，查询用户昵称
                SysUser user = userMapper.selectUserById(record.getLikeToId());
                String userName = "";
                if (user == null) {
                    userName = "用户不存在";
                    likeVO.setLikeToName(userName);
                } else {
                    if (Math.toIntExact(userId) == record.getCreateId()) {
                        userName = "我";
                    } else {
                        userName = record.getCreateBy();
                    }
                    likeVO.setLikeToName(user.getNickName());
                }
                // 根据点亮类型设置已删除的提示信息
                if (record.getLikeType() == 0) {
                    likeVO.setCommentTitle(type == 0 ? "我点亮了" + userName + "发布的帖子：" + "该帖子已被删除" : userName + "点亮了我发布的帖子：" + "该帖子已被删除");
                } else {
                    likeVO.setCommentTitle(type == 0 ? "我点亮了" + userName + "发布的评论：" + "该评论已被删除" : userName + "点亮了我发布的评论：" + "该评论已被删除");
                }
            }
            if(type == 1){
                // PlatformFFeedback platformFForum1 = null;
                // if (likeVO.getLikeType() == 0) {
                //     platformFForum1 = feedbackMapper.selectById(likeVO.getObjectId());
                // } else {
                //     PlatformFFeedback platformFForum2 = feedbackMapper.selectById(likeVO.getObjectId());
                //     if (null != platformFForum2) {
                //         platformFForum1 = feedbackMapper.selectById(platformFForum2.getTopId());
                //     }
                // }
                // if (null != platformFForum1) {
                //     SysUser user1 = userMapper.selectUserById(Long.valueOf(platformFForum1.getCreateId()));
                //     if (null != user1) {
                //         if (null != user1.getAvatar()) {
                //             likeVO.setCreateUrl(user1.getAvatar());
                //         }
                //     }
                // }
                SysUser user = userMapper.selectUserById(Long.valueOf(likeVO.getCreateId()));
                if (null != user) {
                    if (null != user.getAvatar()) {
                        likeVO.setCreateUrl(user.getAvatar());
                    }
                }
            }else {
                SysUser user = userMapper.selectUserById(SecurityUtils.getUserId());
                if (null != user) {
                    if (null != user.getAvatar()) {
                        likeVO.setCreateUrl(user.getAvatar());
                    }
                }
            }
            likeVOList.add(likeVO);
        }
        platformFLikeVOPage.setRecords(likeVOList);
        return new AjaxResult(HttpStatus.SUCCESS, "获取列表成功", platformFLikeVOPage);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public AjaxResult deleteFeedbackLike(Long[] ids) {
        int i1 = feedbackLikeMapper.deleteBatchIds(Arrays.asList(ids));
        if (i1 == 0) {
            throw new RuntimeException("删除点亮失败");
        }
        return new AjaxResult(HttpStatus.SUCCESS, "删除点亮成功");
    }
}
